import os
import threading
from datetime import datetime
from src.database.dao_factory import DAOFactory
from src.modules.whoosh_processor import WhooshProcessor
from src.utils.logger import log_info, log_error
from src.config import STATIC_ROOT_DIR
from src.utils.util import Util

class SearchController:
    def __init__(self):
        self.whoosh_processor = WhooshProcessor()
        self.running = False
        self.thread = None
        self.log_messages = []
        self.status = "idle"
        self.dao_factory = DAOFactory.get_instance()

    def search_videos(self, query, category=None, start_date=None, end_date=None, 
                      max_duration=None,
                      page=1, page_size=10):
        try:
            log_info(f"搜索视频: 分类={category}, 关键词={query}, 时间范围={start_date}至{end_date}")
            
            # 先处理自定义类别的特殊情况
            if category == "自定义":
                log_info(f"检测到自定义类别，将使用直接文件路径: {query}")
                return Util.get_custom_files(query)

            # 调用whoosh_processor的search方法搜索视频
            search_videos = self.whoosh_processor.search(
                category=category,
                query_str=query, 
                start_date=start_date, 
                end_date=end_date,
                limit=page_size,
                max_duration=max_duration,
            )
            video_ids = [search_video['video_id'] for search_video in search_videos]
            videos = self.dao_factory.get_video_dao().get_by_ids(video_ids)
            results = []
            for video in videos:
                results.append({
                    'video_id': video.id,
                    'local_path': video.local_path,
                    'download_at': video.download_at,
                    'duration': video.duration,
                    'username': video.user.username if video.user else "未知用户",
                    "description": video.title,
                    })
            return results
            
        except Exception as e:
            raise Exception(f"搜索视频时发生错误: {e}")

    def get_categories(self):
        try:
            log_info("获取所有分类")
            categories = self.dao_factory.get_monitored_user_dao().get_categories()
            return {"success": True, "data": categories}
        except Exception as e:
            log_error(f"获取分类错误: {e}")
            return {"success": False, "message": str(e)}
    
    def update_search_index(self):
        if self.running:
            return {"success": False, "message": "索引更新已在进行中"}
            
        self.running = True
        self.status = "running"
        self.thread = threading.Thread(target=self._update_index_thread)
        self.thread.daemon = True
        self.thread.start()
        
        return {"success": True, "message": "开始更新搜索索引"}
        
    def _update_index_thread(self):
        try:
            self._log("开始更新视频搜索索引...")
            
            # 更新索引
            self.whoosh_processor.init_videos()
            
            self._log("搜索索引更新完成")
        except Exception as e:
            self._log(f"更新索引过程中出错: {e}")
            log_error(f"更新索引错误: {e}")
        finally:
            self.running = False
            self.status = "completed"
            
    def _log(self, message):
        log_info(message)
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = {"timestamp": timestamp, "message": message}
        self.log_messages.append(log_entry)
        if len(self.log_messages) > 1000:
            self.log_messages = self.log_messages[-1000:]
            
    def get_status(self):
        return {
            "status": self.status,
            "running": self.running,
            "logs": self.log_messages
        }

    def get_group_audio(self, group_id):
        try:
            log_info(f"获取分组音频: 分组ID={group_id}")
            audio_files = self.dao_factory.get_uploaded_file_dao().get_by_group_id(group_id=group_id, file_type='audio')
            return {
                "success": True,
                "data": audio_files
            }
        except Exception as e:
            log_error(f"获取分组音频错误: {e}")
            return {"success": False, "message": str(e)}
        
    def get_audio_history(self, page=1, page_size=10):
        """
        获取音频上传历史记录
        
        :param page: 页码
        :param page_size: 每页记录数
        :return: 包含音频记录的分页结果
        """
        log_info(f"获取音频历史记录: 页码={page}, 每页记录数={page_size}")
        try:
            result = self.dao_factory.get_uploaded_file_dao().get_audio_files(page, page_size)
            return result
        except Exception as e:
            log_error(f"获取音频历史记录失败: {e}")
            return {"success": False, "message": f"获取音频历史记录失败: {e}"}
        
    def get_video_history(self, page=1, page_size=10):
        """
        获取视频上传历史记录
        
        :param page: 页码
        :param page_size: 每页记录数
        :return: 包含视频记录的分页结果
        """
        log_info(f"获取视频历史记录: 页码={page}, 每页记录数={page_size}")
        try:
            result = self.dao_factory.get_generated_video_dao().get_paginated(page, page_size)
            return result
        except Exception as e:
            log_error(f"获取视频历史记录失败: {e}")
            return {"success": False, "message": f"获取视频历史记录失败: {e}"}


    def get_transition_effects(self):
        """
        获取所有可用的转场效果
        
        :return: 包含转场效果列表的响应
        """
        log_info("获取所有转场效果")
        return [
                { "id": "fade", "name": "Fade", "description": "淡入淡出效果，常用于视频开头或结尾" },
                { "id": "wipeleft", "name": "Wipe Left", "description": "从右向左滑动过渡" },
                { "id": "wiperight", "name": "Wipe Right", "description": "从左向右滑动过渡" },
                { "id": "wipeup", "name": "Wipe Up", "description": "从下往上滑动过渡" },
                { "id": "wipedown", "name": "Wipe Down", "description": "从上往下滑动过渡" },
                { "id": "slideleft", "name": "Slide Left", "description": "旧画面向左滑出，新画面滑入" },
                { "id": "slideright", "name": "Slide Right", "description": "旧画面向右滑出，新画面滑入" },
                { "id": "slideup", "name": "Slide Up", "description": "旧画面向上滑出，新画面滑入" },
                { "id": "slidedown", "name": "Slide Down", "description": "旧画面向下滑出，新画面滑入" },
                { "id": "circlecrop", "name": "Circle Crop", "description": "以圆形裁剪方式切换" },
                { "id": "rectcrop", "name": "Rectangle Crop", "description": "以矩形裁剪方式切换" },
                { "id": "distance", "name": "Distance", "description": "通过缩小拉远实现过渡" },
                { "id": "fadeblack", "name": "Fade to Black", "description": "渐变至黑色再切换" },
                { "id": "fadewhite", "name": "Fade to White", "description": "渐变至白色再切换" },
                { "id": "radial", "name": "Radial", "description": "放射状过渡效果" },
                { "id": "smoothleft", "name": "Smooth Left", "description": "平滑向左切换" },
                { "id": "smoothright", "name": "Smooth Right", "description": "平滑向右切换" },
                { "id": "smoothup", "name": "Smooth Up", "description": "平滑向上切换" },
                { "id": "smoothdown", "name": "Smooth Down", "description": "平滑向下切换" },
                { "id": "circleopen", "name": "Circle Open", "description": "从圆心向外打开" },
                { "id": "circleclose", "name": "Circle Close", "description": "从外向内圆形关闭" },
                { "id": "vertopen", "name": "Vertical Open", "description": "从中间垂直展开" },
                { "id": "vertclose", "name": "Vertical Close", "description": "从两边垂直关闭" },
                { "id": "horzopen", "name": "Horizontal Open", "description": "从中间水平展开" },
                { "id": "horzclose", "name": "Horizontal Close", "description": "从两边水平关闭" },
                { "id": "dissolve", "name": "Dissolve", "description": "通过像素随机透明实现溶解过渡" },
                { "id": "pixelize", "name": "Pixelize", "description": "通过像素化图像进行过渡" },
                { "id": "diagtl", "name": "Diagonal Top Left", "description": "从左上对角线方向切换" },
                { "id": "diagtr", "name": "Diagonal Top Right", "description": "从右上对角线方向切换" },
                { "id": "diagbl", "name": "Diagonal Bottom Left", "description": "从左下对角线方向切换" },
                { "id": "diagbr", "name": "Diagonal Bottom Right", "description": "从右下对角线方向切换" },
                { "id": "hlslice", "name": "Horizontal Left Slice", "description": "水平从左向右切片切换" },
                { "id": "hrslice", "name": "Horizontal Right Slice", "description": "水平从右向左切片切换" },
                { "id": "vuslice", "name": "Vertical Up Slice", "description": "垂直从下向上切片切换" },
                { "id": "vdslice", "name": "Vertical Down Slice", "description": "垂直从上向下切片切换" },
                { "id": "hblur", "name": "Horizontal Blur", "description": "通过水平模糊实现过渡" },
                { "id": "wipetl", "name": "Wipe Top Left", "description": "从左上角擦除切换" },
                { "id": "wipetr", "name": "Wipe Top Right", "description": "从右上角擦除切换" },
                { "id": "wipebl", "name": "Wipe Bottom Left", "description": "从左下角擦除切换" },
                { "id": "wipebr", "name": "Wipe Bottom Right", "description": "从右下角擦除切换" },
                { "id": "squeezeh", "name": "Squeeze Horizontal", "description": "水平收缩切换" },
                { "id": "squeezev", "name": "Squeeze Vertical", "description": "垂直收缩切换" },
                { "id": "zoom", "name": "Zoom", "description": "通过缩放实现场景切换" },
                { "id": "crossfade", "name": "Cross Fade", "description": "交叉淡入淡出，两个场景平滑过渡" },
                { "id": "push", "name": "Push", "description": "新画面推动旧画面切换" }
            ]

    def get_suggest_tags(self,category, query, limit=10):
        """
        获取搜索建议标签
        
        :param query: 用户输入的查询关键词
        :return: 包含建议标签的列表
        """
        log_info(f"获取搜索建议标签: 查询关键词={query}")
        try:
            # 调用whoosh_processor的_search_tags方法获取建议标签
            tags = self.whoosh_processor.get_tag_suggestions(category=category, query_str=query, limit=limit)
            return {"success": True, "data": tags}
        except Exception as e:
            log_error(f"获取搜索建议标签错误: {e}")
            return {"success": False, "message": str(e)}


    def get_intro_outro_videos(self, video_type=None):
        """
        获取可用的片头片尾视频列表
        
        :param video_type: 视频类型，不指定则返回所有类型
        :return: 视频列表
        """
        try:
            file_dao = self.dao_factory.get_uploaded_file_dao()
            
            # 调用DAO方法获取视频列表
            return file_dao.get_intro_outro_videos(video_type)
        except Exception as e:
            log_error(f"获取片头片尾视频时出错: {e}")
            return {"success": False, "message": str(e)}